import datetime
import json
import os
import traceback

from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import APIView

from pets import models
from pets.api.serializer import PetClsSerializer
from tools.decorators import get_request_ip
from tools.pages import Mypage
from tools.tool import get_time_to_file_name, get_file_type


@method_decorator(get_request_ip, name='dispatch')
class PetCls(APIView):
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            # 1.狗    2.猫
            body = request.query_params.dict()
            name = body.get('name')
            search_dict = {}
            if name:
                search_dict['name__icontains'] = name
            items = models.PetCls.objects.filter(**search_dict).order_by('id')
            # total = items.count()
            # page = Mypage()
            # page_list = page.paginate_queryset(items, request, view=self)

            cats = items.filter(type_id=2)
            dogs = items.filter(type_id=1)

            ser_cat = PetClsSerializer(cats, many=True)
            ser_dog = PetClsSerializer(dogs, many=True)
            resp = {"code": 1, "cat": ser_cat.data, 'dog': ser_dog.data}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            # print(body)
            file = body.get('img')
            if file:
                name = get_time_to_file_name()
                fname, ftype = get_file_type(str(file))
                file_path = '/{}/{}'.format('img_cls', name + ftype)
                open_path = settings.MEDIA_ROOT + file_path
                with open(open_path, 'wb') as f:
                    f.write(file.read())
                body['path'] = file_path

                # name = get_time_to_file_name()
                # body['name'] = name

                ser = PetClsSerializer(data=body)
                if ser.is_valid():
                    ser.save()
                    resp = {"code": 1, "data": ser.data}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            id = body.get('id')
            file = body.get('img')
            if file:
                name = get_time_to_file_name()
                fname, ftype = get_file_type(str(file))
                file_path = '/{}/{}'.format('img_cls', name + ftype)
                open_path = settings.MEDIA_ROOT + file_path
                with open(open_path, 'wb') as f:
                    f.write(file.read())
                body['path'] = file_path
            item = models.PetCls.objects.get(id=id)
            ser = PetClsSerializer(instance=item, data=body)
            if ser.is_valid():
                ser.save()
                resp = {"code": 1, "data": ser.data}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            id = body.get('id')
            models.PetCls.objects.filter(id__in=id).delete()
            resp = {"code": 1, "data": li}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

